module client.MsgServerClient;

import hunt.logging;
import hunt.util.Serialize;
import std.conv : to;
import msgtrans;
import std.algorithm.mutation : SwapStrategy;
import std.algorithm.sorting;
import core.thread;
import message.Constants;

static struct MsgServerNode {
  string id;
  MessageTransportClient client;
}

/**
 * MsgServer长连接对象
 */
class MsgServerClient
{
  private __gshared MsgServerClient _instance;

  private MsgServerNode[] _forwardClientMap;

  private uint _size = 0;

  static public MsgServerClient getInstance()
  {
    if (_instance is null)
    {
      _instance = new MsgServerClient();
    }
    return _instance;
  }

  public void addForwardClient(string id , MessageTransportClient client)
  {
    synchronized(this){
      _forwardClientMap ~= MsgServerNode(id,client);
      multiSort!("a.id < b.id", SwapStrategy.unstable)(_forwardClientMap);
      _size += 1;
    }
  }

  public MessageTransportClient getForwardClient(string id)
  {
    MessageTransportClient client = null;
    synchronized(this){
      client =  _forwardClientMap[to!int(id) % _size].client;
      if (client.isClosed)
      {
        logInfo("MessageTransportClient closed!!!!!!");
        while (true)
        {
          client.connect();
          logInfo("isConnected :%s",client.isConnected );
          if(client.isConnected)
          {
            client.send(new MessageBuffer(MESSAGE.CMD_REGISTER_GATESERVER , []));
            break;
          }
          Thread.sleep(2.seconds);
        }
      }
    }
    return client;
  }
}

